import { createRouter, createWebHashHistory } from 'vue-router'
import store from '@/store'
import NProgress from 'nprogress'
import { Layout } from '@/layouts'
import { title, titleReverse } from '@/config'

//固定路由
const constantRoutes = [
  {
    path: '',
    name: 'home',
    component: () => import('@/views/home'),
    meta: { title: '首页', requiresAuth: true },
  },
]

// 初始化路由
const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login'),
    meta: { title: '登录' },
  },
  {
    path: '/404',
    name: '404',
    component: () => import('@/views/error/404'),
    meta: { title: '404' },
  },
  {
    path: '/403',
    name: '403',
    component: () => import('@/views/error/403'),
    meta: { title: '403' },
  },
  {
    path: '/',
    name: 'layout',
    component: Layout, // 布局框架
    children: [...constantRoutes],
  },
]

const router = createRouter({
  history: createWebHashHistory(),
  routes,
})

// 路由请求前
router.beforeEach((to, _from, next) => {
  // 每次切换页面时，调用进度条
  NProgress.start()

  if (to.path === '/login' || to.path === '/404' || to.path === '/403') {
    //登录页直接通过
    next()
  } else if (store.getters['user/menus'].length == 0) {
    // 判断是否刷新页面,重置动态菜单
    store
      .dispatch('user/resetMenus')
      .then(() => {
        if (store.getters['user/menus'].length > 0) {
          next({ ...to, replace: true })
        } else {
          next({ name: 'page403' })
        }
      })
      .catch(() => {
        next({ name: 'login' })
      })
  } else if (to.matched.some((record) => record.meta.requiresAuth)) {
    // 判断是否需要验证路由权限
    if (!store.getters['user/accessToken']) {
      next({ name: 'login' })
    } else {
      next()
    }
  } else {
    next()
  }
})

// 路由请求后
router.afterEach((to) => {
  //修改标题
  if (to.meta.title) {
    //标题是否反转 如果为false:"page - title"，如果为ture:"title - page"
    if (titleReverse) {
      document.title = title + ' - ' + to.meta.title
    } else {
      document.title = to.meta.title + ' - ' + title
    }
  } else {
    document.title = title
  }
  // 在即将进入新的页面组件前，关闭掉进度条
  NProgress.done()
})

export default router

//添加异步路由
export function addAsyncRoutes(menus) {
  // 动态添加布局路由(添加与现有途径名称相同的途径，会先删除路由，再添加路由)
  router.addRoute({
    path: '/',
    name: 'layout',
    component: Layout, // 布局框架
    children: [...constantRoutes],
  })
  // 动态添加子路由
  menus.forEach((items) => {
    items.children.forEach((item) => {
      router.addRoute('layout', {
        path: items.id + '/' + item.id,
        name: item.id,
        component: () => import('@/views/home'),
        meta: { title: item.title, requiresAuth: true },
      })
    })
  })
  // 末尾添加404路由
  router.addRoute('layout', {
    path: '/:catchAll(.*)',
    redirect: '/404',
  })
}
